/**
 * Copyright (c) 2014-2018, huli.com
 * All rights reserved.
 */
package com.xiaohujr.xuexue.javaguide;

/**
 * 基础包装类.
 *
 * @author Xue Xue (xuexue1@huli.com)
 * @version $Id$
 * @since 2020/1/16
 */
public class BasicWrapperMain {

    //直接用常量初始化时，会对对象做缓存，因此a和b指向的是同一个对象.
    public static String integerTest1() {
        Integer a = 3;
        Integer b = 3;
        System.out.println(a == b);
        Integer c = new Integer(4);
        Integer d = new Integer(4);
        System.out.println(c == d);
        return "";
    }

    //double精度的文章
    //https://blog.csdn.net/weixin_44588495/article/details/97615664
    public static String doubleTest1() {
        Double a = 1.0d - 0.9d;
        Double b = 0.9d - 0.8d;
        System.out.println(a.equals(b));
        System.out.println(a == b);
        return "";
    }

    public static String doubleTest2() {
        double a = 0.3d;
        System.out.println(0.2d + 0.1d);
        System.out.println(a);
        return "";
    }

    /**
     * 浮点数精度不够，虽然能表示范围，但精度被砍断，无法像double一样，所以equals和==都是false
     * BigDecimal(String)可以防止精度丢失,如果直接传double,会使用Double.toString,导致对尾数进行了阶段,导致精度丢失.
     */
    public static String floatTest1() {
        Float a = 1.0f - 0.9f;
        Float b = 0.9f - 0.8f;
        System.out.println(a.equals(b));
        System.out.println(a == b);
        return "";
    }

    public static void main(String[] args) {

        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        //默认IntegerCache.low 是-127，Integer.high是128，如果在这个区间内，他就会把变量i当做一个变量，放到内存中；但如果不在这个范围内，就会去new一个Integer对象
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        System.out.println(c == d);
        System.out.println(e == f);
        System.out.println(c == (a + b));
        System.out.println(c.equals(a + b));
        System.out.println(g == (a + b));
        System.out.println(g.equals(a + b));

        integerTest1();
        doubleTest1();
        doubleTest2();
        floatTest1();
    }
}
